import { Component, OnInit } from "@angular/core";
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router } from "@angular/router"; //路由引入

declare var $: any;
@Component({
  selector: "adverse-causes",
  templateUrl: "./adverse-causes.component.html",
  styleUrls: ["./adverse-causes.css"],
})
export class AdverseCausesComponent implements OnInit {
  addAdverse: any = {
    type: 1,
    name: '',
    sort: 0
  }
  typeOption: any = [
    {
      text: 'SMT检测不良原因',
      value: 1
    }, {
      text: 'PCBA烧录测试不良原因',
      value: 2
    }, {
      text: '主机组装测试不良原因',
      value: 3
    }
  ]
  oneList: any = [];
  twoList: any = [];
  threeList: any = [];
  oneSelected: string = ''; // 一级表格选中的id
  twoSelected: string = ''; // 二级表格选中的id
  threeSelected: string = ''; // 三级表格选中的id
  oneKey: string = ''; // 输入的一级搜索
  twoKey: string = ''; // 输入的二级搜索
  threeKey: string = ''; // 输入的三级搜索
  twoName: string = '';
  threeName: string = '';
  typeName: string = ''
  editState: boolean = false; // 编辑状态
  editId: string = '';
  type: string | number = ''; //排序弹框的type

  // 权限
  addPermission: boolean = false
  editPermission: boolean = false
  sortPermission: boolean = false

  constructor(private jsonApiService: JsonApiService, private router: Router) { }
  ngOnInit() {
    this.initBtn()
    this.request1()
    this.request2()
    this.request3()
    System.import('script-loader!smartadmin-plugins/bower_components/jquery-nestable/jquery.nestable.js').then(() => { })
  }
  //初始化权限按钮
  initBtn() {
    const btnData = JSON.parse(decodeURIComponent(localStorage.getItem('cargpsw_supplyChain:adverseCauses')))
    if (!btnData) {
      return
    }
    for (let item of btnData) {
      if (item.sourceKey === 'adverseCauses:addBtn' && item.parentId) {
        this.addPermission = true
      }
      if (item.sourceKey === 'adverseCauses:sortBtn' && item.parentId) {
        this.sortPermission = true
      }
      if (item.sourceKey === 'adverseCauses:editBtn' && item.parentId) {
        this.editPermission = true
      }
    }
  }
  //table刷新
  refresh() {
    this.request1()
    this.request2()
    this.request3()
  }
  request1() {
    let data = {
      type: 1,
      name: this.oneKey.trim()
    }
    this.jsonApiService.http_obj("badReasonConfig/queryBadReasonConfigList.html", data).subscribe((result) => {
      if (result.success) {
        this.oneList = JSON.parse(JSON.stringify(result.data))
      } else {
        this.jsonApiService.message(result.message);
      }
    });
  }
  request2() {
    let data = {
      type: 2,
      name: this.twoKey.trim()
    }
    this.jsonApiService.http_obj("badReasonConfig/queryBadReasonConfigList.html", data).subscribe((result) => {
      if (result.success) {
        this.twoList = JSON.parse(JSON.stringify(result.data))
      } else {
        this.jsonApiService.message(result.message);
      }
    });
  }
  request3() {
    let data = {
      type: 3,
      name: this.threeKey.trim()
    }
    this.jsonApiService.http_obj("badReasonConfig/queryBadReasonConfigList.html", data).subscribe((result) => {
      if (result.success) {
        this.threeList = JSON.parse(JSON.stringify(result.data))
      } else {
        this.jsonApiService.message(result.message);
      }
    });
  }

  // 添加
  addShowModal(modal) {
    this.refresh()
    this.editState = false;
    for (let key in this.addAdverse) {
      this.addAdverse[key] = '';
    }
    this.addAdverse.type = 1;
    this.oneSelected = '';
    this.twoSelected = '';
    this.threeSelected = '';
    modal.show();
  }
  addAdverseClose(modal) {
    modal.hide();
  }
  // 提交添加
  addAdverseSubmit(modal) {
    if (!this.addAdverse.name) {
      this.jsonApiService.message('请填写不良原因名称');
      return;
    }
    if (this.addAdverse.name.length > 20) {
      this.jsonApiService.message('不良原因名称字符串不能大于20个字符');
      return;
    }
    let url = 'badReasonConfig/addBadReasonConfig.html'
    if (this.editState) {
      this.addAdverse.id = this.editId;
      url = 'badReasonConfig/updateBadReasonConfig.html'
    }
    this.addAdverse.name = this.addAdverse.name.trim()
    this.jsonApiService.http_obj(url, this.addAdverse).subscribe((result) => {
      this.jsonApiService.message(result.message);
      if (result.success) {
        if (this.addAdverse.type == 1) {
          this.request1()
        } else if (this.addAdverse.type == 2) {
          this.request2()
        } else {
          this.request3()
        }
        modal.hide();
      }
    });
  }
  // 编辑
  regionEdit(id, modal) {
    this.editState = true;
    this.editId = id;
    var editList = []
    if(this.type == 1){
      editList = JSON.parse(JSON.stringify(this.oneList))
    }else if(this.type == 2){
      editList = JSON.parse(JSON.stringify(this.twoList))
    } else if(this.type == 3){
      editList = JSON.parse(JSON.stringify(this.threeList))
    }
    for(let i=0;i< editList.length;i++){
      if(editList[i].id == id){
        this.addAdverse = Object.assign({}, editList[i])
      }
    }
    modal.show()
  }
  // 选中
  rowSelectEvent(row, type) {
    this.type = type
    if (type == 1) {
      this.oneSelected = row.id;
      this.typeName = 'SMT检测不良原因'
    } else if (type == 2) {
      this.twoSelected = row.id;
      this.typeName = 'PCBA烧录测试不良原因'
    } else {
      this.threeSelected = row.id;
      this.typeName = '主机组装测试不良原因'
    }
    this.addAdverse = Object.assign({}, row)
  }
  // 搜索
  tableSearch(type) {
    let name = '';
    if (type == 1) {
      name = this.oneKey;
    } else if (type == 2) {
      name = this.twoKey;
    } else {
      name = this.threeKey;
    }
    let data = {
      type: type,
      name: name
    }
    this.jsonApiService.http_obj("badReasonConfig/queryBadReasonConfigList.html", data).subscribe((result) => {
      this.oneSelected = '';
      this.twoSelected = '';
      this.threeSelected = '';
      if (type == 1) {
        this.oneList = JSON.parse(JSON.stringify(result.data)) || [];
      } else if (type == 2) {
        this.twoList = JSON.parse(JSON.stringify(result.data)) || [];
      } else {
        this.threeList = JSON.parse(JSON.stringify(result.data)) || [];
      }
    });
  }


  /**
   * 排序
   * 
   */

  //菜单排序
  menu_sort(modal, type) {
    modal.show();
    this.type = type
    if (type == 1) {
      this.typeName = 'SMT检测不良原因'
    } else if (type == 2) {
      this.typeName = 'PCBA烧录测试不良原因'
    } else {
      this.typeName = '主机组装测试不良原因'
    }
    this.showMenu();
  }

  //关闭菜单排序
  modalClose(modal) {
    modal.hide();
    $("#nestableList").html("");
  }

  //确定菜单排序
  menuControlSubmit(modal) {
    var setMenuList = $(".dd-handle");
    var menuListData = [];
    var that = this;
    // 确定框
    this.jsonApiService.confirm_message("此操作将永久调整顺序,确认是否修改?").then(() => {

      for (var i = 0; i < setMenuList.length; i++) {
        var menuList;
        menuList = {
          "id": setMenuList[i].dataset.pcode,
          "sort": parseInt(setMenuList[i].dataset.order),
          "name": setMenuList[i].innerText,
        }
        menuListData.push(menuList)
      }

      for (var j = 0; j < menuListData.length; j++) {
        menuListData[j].sort = j + 1;
        menuListData[j].type = that.type
      }

      that.jsonApiService.json_http("badReasonConfig/updateBadReasonConfigList.html", JSON.stringify(menuListData)).subscribe(data => {
        // that.jsonApiService.message(data.message);
        if (data.success) {
          that.modalClose(modal);
          if (this.type == 1) {
            this.request1()
          } else if (this.type == 2) {
            this.request2()
          } else {
            this.request3()
          }
        }
      })

    }, function () {
    });
  }
  showMenu() {
    $("#nestableList").html("");
    var _htmlUIMenuList;
    // //请求全部表单的接口
    let resoureData = []
    if (this.type == 1) {
      resoureData = JSON.parse(JSON.stringify(this.oneList))
    } else if (this.type == 2) {
      resoureData = JSON.parse(JSON.stringify(this.twoList))
    } else {
      resoureData = JSON.parse(JSON.stringify(this.threeList))
    }

    for (let i = 0; i < resoureData.length; i++) {
      let order = resoureData[i].sort == null ? i + 1 : resoureData[i].sort
      _htmlUIMenuList = '<li class="dd-item" data-pcode="' + resoureData[i].id + '"><div class="dd-handle" data-pcode="' + resoureData[i].id + '" data-order="' + order + '"> ' + resoureData[i].name + '</div></li>';
      $("#nestableList").append(_htmlUIMenuList);
    }

    $('#nestable').nestable({
      maxDepth: 0,
      scroll: true,
      scrollSensitivity: 1,
    });
  }
}
